﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GradeBook.Daos;
using GradeBook.Models;
using GradeBook.Security;

namespace GradeBook.Controllers
{
    public class StudentController : Controller
    {
        //
        // GET: /Student/

        [Authorize(Roles = "STUDENT")]
        public ActionResult Cabinet()
        {
            return View(TaskDao.LoadByUserId(
                MemShPrvd.CurrUser().Id
                ));
        }

        [Authorize(Roles = "STUDENT")]
        public ActionResult Task(int? taskId)
        {
            if (taskId.HasValue)
            {
                Task task = TaskDao.GetById((int)taskId);
                if (task.OwnerId != null)
                {
                    using (GradeBookEntities db = new GradeBookEntities())
                    {
                        int userId = MemShPrvd.CurrUser().Id;
                        return View(
                            new TaskInfo
                                {
                                    Id = task.Id,
                                    Description = task.Description,
                                    OwnerId = task.OwnerId,
                                    Conclusion = db.RelTaskUser.First(m => m.TaskId == taskId && m.UserId == userId).Conclusion
                                });
                    }
                }
            }
            return RedirectToAction("Cabinet", "Student");
        }

        [Authorize(Roles = "STUDENT")]
        [HttpPost]
        public ActionResult Task(int? taskId, TaskInfo taskInfo)
        {
            using (GradeBookEntities db = new GradeBookEntities())
            {
                int userId = MemShPrvd.CurrUser().Id;
                RelTaskUser relTaskUser = db.RelTaskUser.First(m => m.TaskId == taskInfo.Id && m.UserId == userId);
                relTaskUser.Conclusion = taskInfo.Conclusion;
                db.SaveChanges();
            }
            return RedirectToAction("Task", "Student", new { taskId });
        }
    }
}
